package reuseplugin.actions.download;

import java.io.File;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import reuseplugin.ClientInterface;
import reuseplugin.views.downloadListe.DownloadView;

import common.itemhandling.Eintrag;
import common.itemhandling.files.Datei;

/**
 * @author Julius Ollesch
 * 
 */
public class DateiDownloadToFolderAction extends Action implements
		ClientInterface {
	private TableViewer viewer;
	private Eintrag eintrag;

	public DateiDownloadToFolderAction(TableViewer v, Eintrag e) {
		super();
		viewer = v;
		eintrag = e;
	}

	@Override
	public void run() {

		ISelection selection = viewer.getSelection();
		Datei datei = (Datei) ((IStructuredSelection) selection)
				.getFirstElement();
		if (datei != null) {
			if (datei.isAufServer()) {
				FileDialog fd = new FileDialog(Display.getCurrent()
						.getActiveShell(), 1 << 13);
				fd.setFileName(datei.getName());
				fd
						.setText(Messages.DateiDownloadToFolderAction_fileDialogTitle);
				String pfad = fd.open();
				if (pfad != null) {
					if (!pfad.equals("")) {
						pfad = new File(pfad).getAbsolutePath();
						if (!c.download(eintrag, datei, pfad)) {
							MessageDialog
									.openError(
											Display.getCurrent()
													.getActiveShell(),
											Messages.DateiDownloadToFolderAction_errorTitle,
											Messages.DateiDownloadToFolderAction_fileCannotBeDownloaded);
						}

					}
				}
			} else {
				MessageDialog
						.openError(
								Display.getCurrent().getActiveShell(),
								Messages.DateiDownloadToFolderAction_errorTitle,
								Messages.DateiDownloadToFolderAction_fileHasNotBeenUploaded);
			}
		}
		viewer.refresh();
		IWorkbenchWindow window = HandlerUtil
				.getActiveWorkbenchWindow(new ExecutionEvent());
		if (window != null) {
			if (window.getActivePage() != null) {
				DownloadView view = (DownloadView) window.getActivePage()
						.findView(DownloadView.ID);
				if (view != null) {
					view.setFocus();
				}
			}
		}
	}

}
